package com.lagou.boot.config;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;


/**
 * 启动配置类
 */
public class SpringApplication {

    public static void run() {
        // 调用tomcatStart方法, 创建, 并启动内嵌tomcat容器
        tomcatStart();
    }

    /**
     * tomcat启动方法
     */
    private static void tomcatStart() {
        try {
            // 1.定义tomcat容器需要的相关参数值
            // 端口号
            int port = 8080;
            // 编码
            String uriEncoding = "UTF-8";
            // web项目存放管理路径
            String webApps = "webapps";
            // 项目根目录
            String classPath = System.getProperty("user.dir");
            // 2.创建tomcat实例
            Tomcat tomcat = new Tomcat();
            // 设置tomcat连接器
            Connector connector = tomcat.getConnector();
            connector.setPort(port);
            connector.setURIEncoding(uriEncoding);
            // 设置host, 创建webapps根目录用于存放解压war包后的项目
            Host host = tomcat.getHost();
            host.setAppBase(webApps);
            Context context = tomcat.addWebapp("/", classPath);
            context.addLifecycleListener(new Tomcat.FixContextListener());
            // 启动tomcat容器
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
